<?php

namespace App\Api\Controllers\Admin;

use App\Api\Requests\AdminUserRequest;
use App\Models\AdminRole;
use App\Models\AdminUser;
use Illuminate\Http\Request;

class AdminUserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword');
        $status  = $request->get('status') ?? '10';
        $limit   = $request->get('limit') ?? 20;
        $page    = $request->get('page') ?? 1;
        $datas   = AdminUser::query()
            ->when($keyword, function ($query, $keyword) {
                $query->where('username', 'like', "%{$keyword}%")
                    ->orwhere('name', 'like', "%{$keyword}%");
            })
            ->where('status', '=', $status)
            ->orderBy('id', 'asc')
            ->paginate($limit, '*', '', $page);

        foreach ($datas as $key => $data) {
            $datas[$key]['roleIdArr'] = array_column($data->roles->toArray(), 'id');
        }

        // 用户状态序列
        $statusMap = AdminUser::STATUS_MAP;

        // 角色列表
        $roleList = AdminRole::fetchRoles();

        return $this->success([
            'list'      => $datas,
            'statusMap' => $statusMap,
            'roleList'  => $roleList,
            'status'    => $status,
        ]);
    }

    /**
     * 存储一个的的后台管理员相关数据
     * @param AdminUserRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(AdminUserRequest $request)
    {
        $request->validated();

        $row = new AdminUser($request->all());
        $row->save();
        $row->addRoles($request->input('roleIdArr'), $row);

        return $this->success($request->all(), '数据创建成功');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(AdminUserRequest $request, $id)
    {
        $row = AdminUser::find($id);
        $request->validated();

        // 默认不更新密码
        $updateData = $request->except(['password']);
        if ($request->filled('password')) {
            $updateData = $request->all();
        }
        $row->update($updateData);

        $roleIdArr = $request->input('roleIdArr') ?? array();
        $row->addRoles($roleIdArr, $row);

        return $this->success($updateData, '数据更新成功');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($idStr)
    {
        if (empty($idStr)) {
            return $this->error('请求处理失败，参数错误。');
        }

        $idArr  = explode(',', $idStr);
        $result = AdminUser::destroy($idArr);

        return $this->success([$idArr], "成功处理 {$result} 条数据。");
    }
}
